<template>
  <div v-if="visible" class="confirm-dialog-overlay" @click.self="handleOverlayClick">
    <div class="confirm-dialog" @click.stop>
      <div class="dialog-content">
        <div class="dialog-title">{{ title }}</div>
        <div v-if="!isEditing && !errorMessage" class="dialog-content-text">{{ content }}</div>
        <div v-if="errorMessage" class="error-message-global">{{ errorMessage }}</div>
        <!-- 编辑模式：用户名输入 -->
        <div v-if="isEditing && editType === 'username'" class="edit-content">
          <div class="input-label">我的名字</div>
          <div class="username-input-wrapper">
            <input
              v-model="editValue"
              type="text"
              class="username-input"
              placeholder="请输入账号名称"
              maxlength="20"
              @input="handleEditInput"
            />
            <div v-if="editValue" class="clear-button" @click="clearEditValue">
              <el-icon><Close /></el-icon>
            </div>
          </div>
          <div class="input-divider"></div>
        </div>
        <!-- 编辑模式：用户昵称输入 -->
        <div v-if="isEditing && editType === 'nickname'" class="edit-content">
          <div class="input-label">我的名字</div>
          <div class="username-input-wrapper">
            <input
              v-model="editValue"
              type="text"
              class="username-input"
              placeholder="请输入用户昵称"
              maxlength="20"
              @input="handleEditInput"
            />
            <div v-if="editValue" class="clear-button" @click="clearEditValue">
              <el-icon><Close /></el-icon>
            </div>
          </div>
          <div class="input-divider"></div>
        </div>
         <!-- 编辑模式：密码输入 -->
         <div v-if="isEditing && editType === 'password'" class="edit-content">
           <div class="password-form">
             <div class="password-item">
               <div class="input-label">原密码</div>
               <div class="password-input-wrapper">
                 <input
                   v-model="passwordForm.oldPassword"
                   :type="showOldPassword ? 'text' : 'password'"
                   class="password-input"
                   placeholder="请输入原密码"
                   @input="handlePasswordInput"
                   @blur="validatePassword"
                 />
                 <div class="eye-button" @click="showOldPassword = !showOldPassword">
                   <el-icon v-if="showOldPassword"><Hide /></el-icon>
                   <el-icon v-else><View /></el-icon>
                 </div>
               </div>
               <div v-if="passwordErrors.oldPassword" class="error-message">{{ passwordErrors.oldPassword }}</div>
               <div class="input-divider"></div>
             </div>
             <div class="password-item">
               <div class="input-label">新密码</div>
               <div class="password-input-wrapper">
                 <input
                   v-model="passwordForm.newPassword"
                   :type="showNewPassword ? 'text' : 'password'"
                   class="password-input"
                   placeholder="请输入新密码"
                   @input="handlePasswordInput"
                   @blur="validatePassword"
                 />
                 <div class="eye-button" @click="showNewPassword = !showNewPassword">
                   <el-icon v-if="showNewPassword"><Hide /></el-icon>
                   <el-icon v-else><View /></el-icon>
                 </div>
               </div>
               <div v-if="passwordErrors.newPassword" class="error-message">{{ passwordErrors.newPassword }}</div>
               <div class="input-divider"></div>
             </div>
             <div class="password-item">
               <div class="input-label">确认新密码</div>
               <div class="password-input-wrapper">
                 <input
                   v-model="passwordForm.confirmPassword"
                   :type="showConfirmPassword ? 'text' : 'password'"
                   class="password-input"
                   placeholder="请再次输入新密码"
                   @input="handlePasswordInput"
                   @blur="validatePassword"
                 />
                 <div class="eye-button" @click="showConfirmPassword = !showConfirmPassword">
                   <el-icon v-if="showConfirmPassword"><Hide /></el-icon>
                   <el-icon v-else><View /></el-icon>
                 </div>
               </div>
               <div v-if="passwordErrors.confirmPassword" class="error-message">{{ passwordErrors.confirmPassword }}</div>
               <div class="input-divider"></div>
             </div>
           </div>
         </div>
      </div>
      <div class="dialog-buttons">
        <button class="dialog-btn cancel-btn" @click="handleCancel">{{ cancelText }}</button>
        <div class="button-divider"></div>
        <button class="dialog-btn confirm-btn" @click="handleConfirm" :disabled="isEditing && editable && editType === 'password' && !isPasswordValid">
          {{ isEditing && editable ? '确认' : confirmText }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Close, View, Hide } from '@element-plus/icons-vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    default: ''
  },
  confirmText: {
    type: String,
    default: '确定'
  },
  cancelText: {
    type: String,
    default: '取消'
  },
  // 是否可编辑
  editable: {
    type: Boolean,
    default: false
  },
  // 编辑类型
  editType: {
    type: String,
    default: 'username'
  },
  // 初始编辑值
  initialValue: {
    type: String,
    default: ''
  },
  // 错误信息
  errorMessage: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:visible', 'confirm', 'cancel'])

const isEditing = ref(false)
const editValue = ref('')
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordErrors = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const showOldPassword = ref(false)
const showNewPassword = ref(false)
const showConfirmPassword = ref(false)

// 验证密码格式
const isPasswordValid = computed(() => {
  const form = passwordForm.value
  if (!form.oldPassword || !form.newPassword || !form.confirmPassword) {
    return false
  }
  if (form.newPassword.length < 6 || form.newPassword.length > 20) {
    return false
  }
  if (form.newPassword !== form.confirmPassword) {
    return false
  }
  return true
})

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (props.editable) {
      isEditing.value = false
      if (props.editType === 'password') {
        passwordForm.value = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } else {
        editValue.value = props.initialValue || ''
      }
    }
  } else {
    isEditing.value = false
    editValue.value = ''
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
    passwordErrors.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
    showOldPassword.value = false
    showNewPassword.value = false
    showConfirmPassword.value = false
  }
})

const handleEditInput = (e) => {
  editValue.value = e.target.value
}

const handlePasswordInput = () => {
  // 密码输入处理，清除错误信息
  passwordErrors.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

const validatePassword = () => {
  passwordErrors.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  
  const form = passwordForm.value
  
  // 验证原密码（只在有非空内容时验证）
  if (form.oldPassword && form.oldPassword.trim() !== '') {
    // 原密码有内容，不需要格式验证，只在提交时验证
  }
  
  // 验证新密码（只在有内容时验证）
  if (form.newPassword && form.newPassword.trim() !== '') {
    if (form.newPassword.length < 6 || form.newPassword.length > 20) {
      passwordErrors.value.newPassword = '密码长度在 6 到 20 个字符'
    }
  }
  
  // 验证确认密码（只在有内容时验证）
  if (form.confirmPassword && form.confirmPassword.trim() !== '') {
    if (form.newPassword && form.newPassword.trim() !== '' && form.newPassword !== form.confirmPassword) {
      passwordErrors.value.confirmPassword = '两次输入的密码不一致'
    }
  }
}

const clearEditValue = () => {
  editValue.value = ''
}

const handleOverlayClick = () => {
  // 如果是密码编辑模式，不允许点击外部关闭
  if (props.editType === 'password') {
    return
  }
  handleCancel()
}

const handleConfirm = () => {
  if (props.editable && !isEditing.value) {
    // 第一次点击确认，进入编辑模式
    isEditing.value = true
  } else if (props.editable && isEditing.value) {
    // 编辑模式下点击确认，提交修改
    if (props.editType === 'password') {
      if (isPasswordValid.value) {
        // 不在这里关闭对话框，由父组件控制
        emit('confirm', {
          oldPassword: passwordForm.value.oldPassword,
          newPassword: passwordForm.value.newPassword,
          confirmPassword: passwordForm.value.confirmPassword
        })
      }
    } else {
      if (editValue.value.trim()) {
        emit('update:visible', false)
        emit('confirm', editValue.value.trim())
        isEditing.value = false
      }
    }
  } else {
    // 非编辑模式，直接确认
    emit('update:visible', false)
    emit('confirm')
  }
}

const handleCancel = () => {
  emit('update:visible', false)
  emit('cancel')
  isEditing.value = false
  editValue.value = ''
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordErrors.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  showOldPassword.value = false
  showNewPassword.value = false
  showConfirmPassword.value = false
}
</script>

<style lang="scss" scoped>
.confirm-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  
  .confirm-dialog {
    width: 88%;
    max-width: 320px;
    background: #ffffff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    .dialog-content {
      padding: 32px 24px 24px 24px;
      text-align: center;
      
      .dialog-title {
        font-size: 18px;
        font-weight: bold;
        color: #000000;
        margin-bottom: 24px;
        line-height: 1.4;
      }
      
      .dialog-content-text {
        font-size: 16px;
        color: #000000;
        line-height: 1.5;
        margin-bottom: 0;
      }
      
      .error-message-global {
        font-size: 14px;
        color: #f56c6c;
        margin-top: 12px;
        text-align: center;
        padding: 8px 12px;
        background: #fef0f0;
        border-radius: 4px;
        line-height: 1.5;
      }
      
      .edit-content {
        .input-label {
          font-size: 14px;
          color: #909399;
          margin-bottom: 12px;
          text-align: left;
        }
        
        .username-input-wrapper {
          display: flex;
          align-items: center;
          position: relative;
          
          .username-input {
            flex: 1;
            border: none;
            background: transparent;
            font-size: 18px;
            color: #000000;
            outline: none;
            padding: 0;
            font-weight: 500;
            
            &::placeholder {
              color: #c0c4cc;
            }
          }
          
          .clear-button {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background: #c0c4cc;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            margin-left: 8px;
            flex-shrink: 0;
            
            .el-icon {
              font-size: 14px;
              color: #ffffff;
            }
            
            &:hover {
              background: #a8abb2;
            }
            
            &:active {
              background: #909399;
            }
          }
        }
        
        .input-divider {
          height: 1px;
          background: #f0f0f0;
          margin-top: 12px;
        }
        
        .password-form {
          text-align: left;
          
          .password-item {
            margin-bottom: 20px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .input-label {
              font-size: 14px;
              color: #909399;
              margin-bottom: 12px;
            }
            
            .password-input-wrapper {
              display: flex;
              align-items: center;
              position: relative;
              
              .password-input {
                flex: 1;
                border: none;
                background: transparent;
                font-size: 18px;
                color: #000000;
                outline: none;
                padding: 0;
                padding-right: 32px;
                font-weight: 500;
                
                &::placeholder {
                  color: #c0c4cc;
                }
              }
              
              .eye-button {
                position: absolute;
                right: 0;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                color: #909399;
                transition: color 0.2s;
                
                &:hover {
                  color: #606266;
                }
                
                .el-icon {
                  font-size: 18px;
                }
              }
            }
            
            .error-message {
              font-size: 12px;
              color: #f56c6c;
              margin-top: 4px;
              text-align: left;
            }
            
            .input-divider {
              height: 1px;
              background: #f0f0f0;
              margin-top: 12px;
            }
          }
        }
      }
    }
    
    .dialog-buttons {
      display: flex;
      border-top: 0.5px solid #e8e8e8;
      
      .dialog-btn {
        flex: 1;
        height: 52px;
        border: none;
        background: #ffffff;
        color: #000000;
        font-size: 16px;
        font-weight: 400;
        cursor: pointer;
        padding: 0;
        transition: background-color 0.2s;
        position: relative;
        
        &:hover {
          background: #fafafa;
        }
        
        &:active {
          background: #f5f5f5;
        }
        
        &.cancel-btn {
          &::after {
            content: '';
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            width: 0.5px;
            background: #e8e8e8;
          }
        }
        
        &.confirm-btn {
          &:disabled {
            background: #e4e7ed !important;
            color: #c0c4cc !important;
            cursor: not-allowed !important;
            
            &:hover {
              background: #e4e7ed !important;
            }
            
            &:active {
              background: #e4e7ed !important;
            }
          }
        }
      }
      
      .button-divider {
        width: 0.5px;
        background: #e8e8e8;
        flex-shrink: 0;
      }
    }
  }
}
</style>

